

package projectx.db;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import projectx.core.base.ProjectXProperties;
import projectx.core.base.ProjectXSystemException;

public class ProjectXConnectionManager {

	//--------------------------------------------------------------------------
	//   S T A T I C M E N B E R S
	//
	//--------------------------------------------------------------------------
	public static final String polarisSchema = ProjectXProperties.getProperty(
			"polaris.db.schema", "spa");

	public static final String polarisMirrorSchema = ProjectXProperties
			.getProperty("polaris.mirror.schema", "spa");

	private static final Logger _log = Logger
			.getLogger(ProjectXConnectionManager.class.getName());

	//--------------------------------------------------------------------------
	//   S T A T I C M E T H O D S
	//
	//--------------------------------------------------------------------------

	public static Connection getConnection() throws ProjectXSystemException,
			ProjectXSQLException {

		Connection conn = null;

		try {
			conn = privateGetConnection(true);

			conn.setAutoCommit(false);

			//setSchema(conn, polarisSchema);

			return conn;
		} catch (SQLException e) {
			if (conn != null)
				try {
					conn.close();
				} catch (SQLException ex) {
				}
			throw new ProjectXSQLException(e);
		}
	}

	public static Connection getMrDbConnection() throws ProjectXSystemException,
			ProjectXSQLException {

		Connection conn = null;

		try {
			conn = privateGetConnection(false);

			conn.setAutoCommit(false);

			//setSchema(conn, polarisMirrorSchema);

			return conn;
		} catch (SQLException e) {
			if (conn != null)
				try {
					conn.close();
				} catch (SQLException ex) {
				}
			throw new ProjectXSQLException(e);
		}
	}

	private static Connection privateGetConnection(boolean isProductDB)
			throws ProjectXSystemException, SQLException {
		if (ProjectXDataSource.isInitialized()) {

			return ProjectXDataSource.getConnection();
		}

		if (!ProjectXDriverManager.isInitialized()) {
			ProjectXDriverManager.initialize();
		}
		if (isProductDB) {
			return ProjectXDriverManager.getConnection();
		} else {
			return ProjectXDriverManager.getMrDbConnection();
		}
	}

	/*
	private static void setSchema(Connection conn, String schema)
			throws SQLException {

		String sql = "SET CURRENT SCHEMA " + schema;

		PreparedStatement ps = null;

		try {

			if (_log.isDebugEnabled()) {
				_log.debug(sql);
			}

			ps = conn.prepareStatement(sql);
			ps.executeUpdate();
		} finally {
			if (ps != null)
				try {
					ps.close();
				} catch (SQLException e) {
				}
		}
	}
	*/
}
